package com.charon.auth.handler;

import com.charon.auth.enumeration.LoginType;
import com.charon.auth.properties.SecurityProperties;
import com.charon.auth.support.SimpleResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: AuthFailureHandler
 * @Description: 认证失败时候的回调
 *                  可以实现AuthenticationFailureHandler，或者使用Security中已经实现该接口的类，
 *                  当前使用的是Security框架中的
 * @Author Charon [248135724@qq.com]
 * @Date 2019/1/20 2:48
 * @Version V 1.0
 */
@Slf4j
@Component
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error("认证失败：AuthFailureHandler："+exception.toString());
        //REDIRECT返回页面，JSON时返回其他
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            //response.getWriter().write(objectMapper.writeValueAsString(exception));
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
        }else {
            //跳到一个错误页面
            super.onAuthenticationFailure(request,response,exception);
        }
    }
}
